﻿using SharpDX;
using SharpDX.DXGI;
using SharpDX.Direct2D1;

using Factory2D = SharpDX.Direct2D1.Factory;
using AlphaMode = SharpDX.Direct2D1.AlphaMode;
using FactoryWrite = SharpDX.DirectWrite.Factory;
using System;
using System.Drawing;

namespace OpenGameEngine.Base
{
    public class Game : GameBaseHardwareLayer
    {
        [Obsolete("No longer used by the engine", false)]
        public Factory2D Factory2D { get; private set; }
        [Obsolete("No longer used by the engine", false)]
        public FactoryWrite FactoryWrite { get; private set; }
        [Obsolete("No longer used by the engine", false)]
        public RenderTarget RenderTarget2D { get; private set; }

        public GameServices Services { get; private set; }

        protected override void Initialize(GameConfiguration config)
        {
            base.Initialize(config);
            Factory2D = new Factory2D();
            using (Surface surface = BackBuffer.QueryInterface<Surface>())
            {
                RenderTargetProperties props = new RenderTargetProperties(
                    new PixelFormat(Format.Unknown, AlphaMode.Premultiplied));

                props.MinLevel = FeatureLevel.Level_DEFAULT;
                props.DpiX = 96;
                props.DpiY = 96;
                RenderTarget2D = new RenderTarget(Factory2D, surface, props);
            }

            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;

            FactoryWrite = new FactoryWrite();

            Services = new GameServices();

            SetInternals(this);
        }

        private static void SetInternals(Game g)
        {
            Globals.RenderTarget = g.RenderTarget2D;
            Globals.FactoryWrite = g.FactoryWrite;
            Globals.Factory2D = g.Factory2D;
        }

        protected override void BeginDraw(GameTime time)
        {
            base.BeginDraw(time);
            RenderTarget2D.BeginDraw();
            RenderTarget2D.Clear(null);
        }

        protected override void EndDraw(GameTime time)
        {
            long tag1;
            long tag2;

            RenderTarget2D.EndDraw(out tag1, out tag2);

            if (tag1 != 0 || tag2 != 0)
                Console.WriteLine("Error ending the drawing: \nTag1: " + tag1 + "\nTag2: " + tag2);

            base.EndDraw(time);
        }
    }
}
